<template>
  <base-breadcrumb class="">
    <!-- 方案审核师管理 -->
    <a-spin :spinning="loading">
      <a-card :bordered="false">
          <title-name title="会议发起"></title-name>
          <custom-form
            ref="customForm"
            :form="form"
            :edit-model="'E'"
            :form-list="formList"
            :rules="rules"
            is-validate
          />
      </a-card>
      <!-- 表格 -->
      <a-card :bordered="false">
        <title-name title="评审方案列表"></title-name>

        <a-button v-if="editable" @click="handleDetial('add')" type="primary" v-btnPermission="'tm_009_add_01'">添加方案</a-button>
        <a-button v-if="!editable" type="primary">导出</a-button>
        <a-table :columns="columns" :data-source="tableData">

          <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>

          <template slot="filesTitle">
            <div style="text-align: center;">
              附件<div style="color: #D9001B;">(联审方案电子版或扫描件、汇报ppt)</div>
            </div>
          </template>

          <template slot="files" slot-scope="text, record">
            <div v-for="(item, index) in [...record.pictures, ...record.rectificationPicture, ...record.otherPicture]">
              <a-popover
                v-if="item"
                :key="item.fileId"
                placement="top"
              >
                <template slot="content">
                  <a
                    :fileId="item.fileId"
                    :fileName="item.fileName"
                    :href="'/api/ycloud-file-center/oper/download?access_token=' + token + '&fileId=' + item.fileId"
                    target="_parent"
                  >下载</a>
                  <a-divider type="vertical" />
                  <a
                    :key="item.fileId"
                    @click="$filePreview(item)"
                  >查看</a>
                </template>
                <a-button
                  size="small"
                  type="link"
                >
                  {{ item.fileName + item.suffixName }}
                </a-button>
              </a-popover>
            </div>
          </template>

          <!-- 操作 -->
          <template slot="operation" slot-scope="text, record">
            <span v-if="editable">
              <a @click="handleDetial('edit', record)">编辑</a>
              <a-divider type="vertical" />
              <a @click="handleDelete(record)">删除</a>
            </span>
            <span v-else>
                <!-- :fileId="item.fileId"
                :fileName="item.fileName"
                :href="'/api/ycloud-file-center/oper/download?access_token=' + token + '&fileId=' + item.fileId"
                target="_parent" -->
              <a
              >导出</a>
            </span>
          </template>
        </a-table>
        <!-- <b-table
          ref="table"
          class="export-table"
          :showPage="false"
          :columns="columns"
          :request="loadData"
          :selectConfig="{rowKey: 'localId'}"
        >

          <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
          <span slot="filesTitle">附件<span style="color: #D9001B;">(联审方案电子版或扫描件、汇报ppt)</span></span>

          <template slot="prefix" slot-scope="ref">
            <a-button @click="handleDetial('add')" type="primary" v-btnPermission="'tm_009_add_01'">添加方案</a-button>
          </template>
        </b-table>
        <s-table
          ref="table"
          class="export-table"
          :showPagination="false"
          :columns="columns"
          :data="loadData"
          :rowKey="'localId'"
        >
          <span slot="filesTitle">附件<span style="color: #D9001B;">(联审方案电子版或扫描件、汇报ppt)</span></span>

          <template slot="operation" slot-scope="text, record">
              <a @click="handleDetial('edit', record)">编辑</a>
              <a-divider type="vertical" />
              <a @click="handleDelete(record)">删除</a>
          </template>
        </s-table> -->
      </a-card>

      <a-card :bordered="false">
        <title-name title="联审意见"></title-name>
      </a-card>
    </a-spin>
    <!-- 页脚操作栏 -->
    <div class="btn_box page-btn-right-top">
      <a-button :disabled="loading" :loading="defloading" v-if="editable" type="primary" class="button_right" @click="save"
        >保存草稿</a-button>

      <a-button :disabled="loading" :loading="subloading" v-if="editable" type="primary" class="button_right" @click="handleSubmit(1)"
        >提交</a-button
      >
      <a-button @click="$close">关闭</a-button>
    </div>

    <dialog-model
      ref="dialogForm"
      :visible.sync="visible.programForm"
      :edit-model="editModel"
      :forms="programForm"
      @confirm="refreshTable"
    >
      <!-- :refresh="handleSearch" -->
      <!-- @updateActiveKey="$emit('update:activeKey', 'compose')" -->
    </dialog-model>
    </base-breadcrumb>
</template>

<script>

import { programMeetAdd, programMeetUpdate, getProgramMeetDetail } from '@/api/technical/meeting'
// import DialogForm from '@/components/DialogForm' // 弹窗
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import SelectOrgPeople from '@/components/Select/SelectOrgPeople' // 人员
import DialogModel from './DialogModel.vue'
import Vue from 'vue'
const columns = [
    {
        title: '序号',
        width: '65px',
        scopedSlots: { customRender: 'serial' },
    },
    {
        title: '分公司',
        dataIndex: 'branchComName',
        key: 'branchComName'
    },
    {
        title: '项目名称',
        dataIndex: 'projectName',
    },
    {
        title: '方案名称',
        dataIndex: 'programName',
    },
    {
        // title: '附件',
        dataIndex: 'files',
        slots: { title: 'filesTitle' },
        scopedSlots: { customRender: 'files' }
    },
    {
        title: '方案类型',
        dataIndex: 'programTypeName',
    },
    {
        title: '项目总工',
        dataIndex: 'zgName',
    },
    {
        title: '专业',
        dataIndex: 'professional',
    },
    {
        title: '主评专家',
        dataIndex: 'mainPeopleName',
    },
    {
        title: '操作',
        dataIndex: 'operation',
        fixed: 'right',
        width: '120px',
        scopedSlots: { customRender: 'operation' },
    },
]
export default {
    name:'a'+Date.now(),
    components: {
      SelectSubCompany,
      SelectProject,
      SelectOrgPeople,
      // DialogForm,
      DialogModel
    },
    data() {
        this.columns = columns
        return {
            token: '',
            visible: {
              programForm: false
            },
            editModel: 'add',
            loading: false, // 加载控件
            defloading: false,
            subloading: false,
            form: {
              orgId: '',
              orgName: '',
              meetingName: '',
              speaker: '',
              meetOption: '',
              meetDate: '',
              address: '',
              evaluationPlanList: []
            }, // 表单
            rules: {
                speaker: [{ required: true, message: '请输入主持人/主讲人', trigger: 'blur' }],
                address: [{ required: true, message: '请输入会议地点', trigger: 'blur' }],
                meetDate: [{ required: true, message: '请选择会议时间', trigger: 'change' }],
                meetOption: [{ required: true, message: '请输入会议说明', trigger: 'blur' }],
            }, // 校验规则

            tableData: [],
            loadData: (parameter) => {
              let that = this
              return new Promise((resolve, reject) => {
                resolve({ code: 200, data: that.tableData })
              })
            },
            curTableId: undefined,
            programForm: {
              // // // 分公司id
              // branchComId: '',
              // // 分公司名称
              // branchComName: '',
              // // 项目id
              // projectId: undefined,
              // // 项目名称
              // projectName: undefined,
              // // 方案类别Id
              // programTypeId: undefined,
              // // 方案类别Name
              // programTypeName: undefined,
              // // 方案id
              // programId: undefined,
              // // 方案id
              // programName: undefined,
              // meetDate: undefined,
              // // 总工id
              // zgId: undefined,
              // // 总工名称
              // zgName: undefined,
              // // 主平专家id
              // mainPeopleId: [],
              // // 主平专家名称
              // mainPeopleName: [],
              // // 专业类别
              // professional: undefined,

              pictures: [],
              rectificationPicture: [],
              otherPicture: []
            },
            programFormRules: {
                projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
            }

        }
    },

    mounted() {
      this.token = Vue.getAcloudProvider().getAccessToken()
      if (this.type == 'add') {
        let curOrg = this.ownOrgList.find((v) => {
          return v.code == this.curTagCode
        })
        this.form.orgId = curOrg?.id
        this.form.orgName = curOrg?.name
      } else {
        this.getDetail()
      }
    },
    computed: {
      type() {
        return this.$route.query.type
      },
      editable() {
        return this.type == 'add' || this.type == 'edit'
      },
      curTagCode() {
        return this.$currentPost().tagCode
      },
      curEmployee() {
        return this.$userInfo().employee.levels
      },
      ownOrgList() {
        let levels = [...this.$userInfo().employee.levels]
        let ownOrg = levels.filter((v) => {
          return v.code === 'CO' || v.code === 'BC'
        })
        ownOrg.forEach((v) => {
          if (v.code == 'CO') v.name = '总部机关'
        })
        return ownOrg
      },
      curTableKey() {
        return this.type == 'add' ? 'localId' : 'id'
      },
      formList() {
        return [
          {
            type: 'a-select',
            keyName: 'orgId',
            label: '所属组织机构',
            disabled: true,
            data: this.ownOrgList,
            replaceFields: {
              label: 'name',
              value: 'id'
            },
          },
          {
            keyName: 'meetingName',
            type: 'a-input',
            // disabled: true,
            label: '会议名称',
          },
          {span: 8},
          {
            keyName: 'speaker',
            type: 'a-input',
            disabled: (!this.editable),
            label: '主持人/主讲人',
          },
          {
            keyName: 'address',
            type: 'a-input',
            disabled: (!this.editable),
            label: '会议地点',
          },
          {
            keyName: 'meetDate',
            type: 'a-date-picker',
            label: '会议时间',
            disabled: (!this.editable),
            attrs: {
              valueFormat: 'YYYY-MM-DD HH:mm',
              showTime: { format: "HH:mm", valueFormat: "HH:mm" },
              format: 'YYYY-MM-DD HH:mm'
            }
          },
          {
            keyName: 'meetOption',
            span: 24,
            type: 'BaseTextarea',
            disabled: (!this.editable),
            label: '会议说明',
          },
        ]
      },
    },
    methods: {
      genID(length) {
        return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36)
      },
      handleDetial(type, record) {
        this.editModel = type
        if (type == 'add') {
          this.programForm = {}
          console.log(this.curTableKey)
          this.$set(this.programForm, this.curTableKey, this.genID(18))
          this.$set(this.programForm, 'branchComId', this.form.orgId)
          this.$set(this.programForm, 'branchComName', this.form.orgName)
        } else {
          this.programForm = { ...record }
        }
        console.log(this.programForm)
        this.visible.programForm = true
      },
      handleDelete(record) {
        this.tableData.forEach((item, idx) => {
          if (item[this.curTableKey] == record[this.curTableKey]) {
            this.tableData.splice(idx, 1)
          }
        })
        // this.tableData = this.tableData.filter(v => v.locakId !== record.locakId)
        //this.$refs.table.refresh()
      },
      refreshTable(e) {
        const row = this.tableData.find((v) => v[this.curTableKey] == e[this.curTableKey])
        if (row) {
          this.tableData = this.tableData.map((v) => {
            if (v[this.curTableKey] == e[this.curTableKey]) {
              v = {...e}
            }
            return v
          })
        } else {
          this.tableData.push({...e})
        }
        //this.$refs.table.refresh()
      },
      getDetail() {
        getProgramMeetDetail(this.$route.query.id).then((res) => {
          if (res.code == 200) {
            const data = res.data
            this.form = data
            this.tableData = data.evaluationPlanList
            console.log(this.tableData)
            //this.$refs.table.refresh()
          }
        })
      },
      save(back = true) {
        const params = { ...this.form }
        params.evaluationPlanList = [...this.tableData]
        console.log(params)
        params.auditStatus = 'DRAFT'
        this.defloading = true
        const api = this.type == 'add' ? programMeetAdd : programMeetUpdate
        api(params).then((res) => {
          this.defloading = false
          console.log(res)
          if (res.code == 200) {
            this.$message.success('保存草稿成功')
            if (back) {
              this.$close()
            } else {
              this.getDetail()
            }
          }
        }).catch(() => {
          this.defloading = false
        })
      },
      handleSubmit() {
        this.$refs.customForm.validate((valid) => {
          if (valid) {
            const params = { ...this.form }
            params.evaluationPlanList = [...this.tableData]
            console.log(params)
            params.auditStatus = 'SUBMITTED'
            const api = this.type == 'add' ? programMeetAdd : programMeetUpdate
            const msg = this.type == 'add' ? '添加' : '编辑'
            this.subloading = true
            api(params).then((res) => {
              this.subloading = false
              if (res.code == 200) {
                this.$message.success(msg+'成功')
                this.$close()
              }
            }).catch(() => {
              this.subloading = false
            })
          } else {
            this.$message.warning("请填写完所有必填项信息")
          }
        })
      }
    },
}
</script>

<style lang="less" scoped>
</style>
